<template>
    <div>
         <input
            class="inputs"
            v-model="inputRef.val"
            v-bind="$attrs"
            @blur="validateInput"
              />
            <div class="error" v-if="inputRef.error">
               * {{inputRef.message}}
            </div>
    </div>
</template>

<script lang="ts">
import { computed, defineComponent,onMounted,PropType,reactive } from 'vue'
import { emitter } from './vForm.vue'
interface RuleProp {
  type: "required" | "email" | "custom";
  message: string;
  validator?: () => boolean;
}
const emailReg = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
export type RulesProp = RuleProp[]
export type TagType = "input" | "textarea"

export default defineComponent({
    props: {
        rules: Array as PropType<RulesProp>,
        tag: {
            type: String as PropType<TagType>,
            default: "input",
        },
        modelValue: String
    },
    inheritSttrs: false,

    setup(props,context) {
        const inputRef = reactive({
            val: computed({
                get:()=> props.modelValue || "",

                set: (val)=> {
                    context.emit("update:modelValue",val)
                }
            }),
            message: "",
            error: false
           
        })
        
        const validateInput = () => {
            if(props.rules) {
                const allpassed = props.rules.every((rule) => {
                    let passed = true;
                    inputRef.message = rule.message;
                    switch(rule.type) {
                        case "required":
                            passed = inputRef.val.trim()  !== "";
                            break;
                        case "email":
                            passed = emailReg.test(inputRef.val)
                            break;
                        default :
                        break;
                    }
                    return passed
                })
                inputRef.error = !allpassed
                return allpassed
            }
            return true;
        }
        onMounted(()=> {
            emitter.emit('form-item-created',validateInput)
        })
        return {
            inputRef,
            validateInput
        }
    },
})
</script>


<style>
.inputs {
  border: 0;
  width: 70%;
  color: #545454;
  background: transparent;
}
.error{
    color: #dc3545;
    position: absolute;
    left: 0;
    bottom: -20px;
    font-size: 10px;
}
</style>